import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { motion } from 'framer-motion';
import { useAuth } from '../contexts/AuthContext';
import { logInfo, logError } from '../logger';
import api from '../services/api';

// 样式组件
const PageContainer = styled.div`
  max-width: 1000px;
  margin: 0 auto;
  padding: 2rem;
  min-height: calc(100vh - 120px);
`;

const Header = styled.header`
  text-align: center;
  margin-bottom: 2rem;
`;

const Title = styled.h1`
  font-size: 2.5rem;
  color: ${props => props.theme.colors.primary};
  margin-bottom: 0.5rem;
`;

const Subtitle = styled.p`
  font-size: 1.2rem;
  color: ${props => props.theme.colors.textSecondary};
  margin-bottom: 2rem;
`;

const HistoryContainer = styled.div`
  background: ${props => props.theme.colors.cardBackground};
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
`;

const HistoryList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
`;

const HistoryItem = styled.div`
  border: 1px solid ${props => props.theme.colors.border};
  border-radius: 8px;
  padding: 1.5rem;
  transition: box-shadow 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
`;

const ItemHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid ${props => props.theme.colors.border};
`;

const ItemName = styled.h3`
  font-size: 1.25rem;
  color: ${props => props.theme.colors.primary};
  margin: 0;
`;

const ItemDate = styled.span`
  color: ${props => props.theme.colors.textSecondary};
  font-size: 0.875rem;
`;

const TagsContainer = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 1rem;
`;

const Tag = styled.span`
  background: ${props => props.theme.colors.primary};
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.75rem;
`;

const TraitsContainer = styled.div`
  margin-bottom: 1rem;
`;

const TraitsTitle = styled.h4`
  color: ${props => props.theme.colors.textPrimary};
  margin: 0 0 0.5rem 0;
  font-size: 1rem;
`;

const TraitsList = styled.ul`
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
`;

const TraitItem = styled.li`
  background: ${props => props.theme.colors.background};
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.875rem;
`;

const InterpretationText = styled.p`
  line-height: 1.6;
  color: ${props => props.theme.colors.textPrimary};
  margin: 0;
`;

const EmptyState = styled.div`
  text-align: center;
  padding: 3rem;
  color: ${props => props.theme.colors.textSecondary};
`;

const LoadingSpinner = styled.div`
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: ${props => props.theme.colors.primary};
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 2rem auto;

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
`;

const ErrorMessage = styled.div`
  background: #fee;
  color: #c33;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
  text-align: center;
`;

const Button = styled.button`
  padding: 0.5rem 1rem;
  background: ${props => props.theme.colors.primary};
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background 0.3s ease;

  &:hover {
    background: ${props => props.theme.colors.primaryHover};
  }
`;

/**
 * 姓名测算历史记录页面组件
 */
const NameAnalysisHistory = () => {
  // 状态管理
  const [history, setHistory] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { user } = useAuth();

  /**
   * 获取用户姓名测算历史记录
   */
  const fetchHistory = async () => {
    if (!user) {
      setError('请先登录查看历史记录');
      setLoading(false);
      return;
    }
    
    try {
      setLoading(true);
      setError(null);
      
      logInfo('获取姓名测算历史记录', { userId: user.id });
      
      // 调用API获取历史记录
      const response = await api.get('/api/name-analysis/my-analyses');
      
      // 设置历史记录
      setHistory(response.data);
      logInfo('获取姓名测算历史记录成功', { 
        userId: user.id, 
        count: response.data.length 
      });
    } catch (err) {
      logError('获取姓名测算历史记录失败', { 
        error: err.message, 
        userId: user?.id 
      });
      
      setError('获取历史记录失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取历史记录
  useEffect(() => {
    fetchHistory();
  }, [user]);

  /**
   * 格式化日期
   * @param {string} dateStr - 日期字符串
   * @returns {string} 格式化后的日期
   */
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <PageContainer>
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <Header>
          <Title>姓名测算历史</Title>
          <Subtitle>查看您之前的姓名测算记录</Subtitle>
        </Header>
        
        <HistoryContainer>
          {loading ? (
            <LoadingSpinner />
          ) : error ? (
            <ErrorMessage>{error}</ErrorMessage>
          ) : history.length === 0 ? (
            <EmptyState>
              <p>暂无姓名测算记录</p>
              <p>开始您的第一次姓名测算吧！</p>
            </EmptyState>
          ) : (
            <HistoryList>
              {history.map((record) => (
                <HistoryItem key={record.id}>
                  <ItemHeader>
                    <ItemName>{record.name}</ItemName>
                    <ItemDate>{formatDate(record.createdAt)}</ItemDate>
                  </ItemHeader>
                  
                  <TagsContainer>
                    {record.positiveTags.map((tag, index) => (
                      <Tag key={index}>{tag}</Tag>
                    ))}
                  </TagsContainer>
                  
                  <TraitsContainer>
                    <TraitsTitle>积极特质</TraitsTitle>
                    <TraitsList>
                      {record.positiveTraits.slice(0, 5).map((trait, index) => (
                        <TraitItem key={index}>{trait}</TraitItem>
                      ))}
                    </TraitsList>
                  </TraitsContainer>
                  
                  <InterpretationText>
                    {record.interpretation.substring(0, 100)}...
                  </InterpretationText>
                </HistoryItem>
              ))}
            </HistoryList>
          )}
        </HistoryContainer>
      </motion.div>
    </PageContainer>
  );
};

export default NameAnalysisHistory;